package com.qinghe.pro.controller.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qinghe.pro.Constants;
import com.qinghe.pro.entity.main.LogInfo;
import com.qinghe.pro.service.main.LogInfoService;
import com.qinghe.pro.shiro.ShiroUser;
import com.qinghe.utils.AjaxObject;
import com.qinghe.utils.FileUtils;
import com.qinghe.utils.SecurityUtils;
import com.qinghe.utils.ServletUtils;
import com.qinghe.utils.Utils;

@Controller
@RequestMapping("/file")
public class FileController {

	@Autowired
	@Qualifier("logInfoServiceImpl")
	private LogInfoService logInfoService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	public @ResponseBody String upload(HttpServletRequest request, MultipartFile file) {
		String path = Constants.getTempPath();
		int size = 1024 * 1024 * 2;// 2M
		return this.upload(request, file, path, size, false);
	}

	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	public @ResponseBody String uploadImg(HttpServletRequest request, MultipartFile file) {
		String path = Constants.getImagePath();
		int size = 1024 * 1024 * 2;// 2M
		return this.upload(request, file, path, size, false);
	}

	@RequestMapping(value = "/apiUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	public @ResponseBody String apiUpload(HttpServletRequest request, MultipartFile file) {
		String path = Constants.getApiPath();
		int size = 1024 * 1024 * 10;// 10M
		return this.upload(request, file, path, size, true);
	}

	/**
	 * 上传
	 * 
	 * @param request
	 * @param file
	 * @param path 路径
	 * @param size 限制大小
	 * @param hasLog 是否写上传记录
	 * 
	 * @return
	 * @author longfei
	 */
	private String upload(HttpServletRequest request, MultipartFile file, String path, int size, boolean hasLog) {
		Map<String, Object> map = new HashMap<String, Object>();
		String fileName = file.getOriginalFilename();
		String fileExt = FileUtils.getFileExt(fileName);
		if (file.getSize() > size) {
			return AjaxObject.newError("文件的大小限制为：" + size/1024/1024 + "M").toString();
		}
		try {
			// 要保存的物理文件名 + 后缀名
			String newFileName = FileUtils.getRealName(fileName) + Utils.DateUtil.format("yyyyMMddHHmmssSSSS", new Date()) + "." + fileExt;
			
			String uploadPath = FileUtils.getFileStorePath(request) + path;
			
			// 构建文件要保存到的目录
			File uploadedFile = new File(uploadPath, newFileName);
			
			org.apache.commons.io.FileUtils.writeByteArrayToFile(uploadedFile, file.getBytes());
			
			map.put("url", path + "/" + newFileName);
			map.put("fileName", newFileName);
			
			if (hasLog) {// 写上传记录
				ShiroUser shiroUser = SecurityUtils.getShiroUser();

				LogInfo logInfo = new LogInfo();
				logInfo.setCreateTime(new Date());
				logInfo.setUsername(shiroUser.getLoginName());
				logInfo.setType("上传记录");
				logInfo.setMessage("上传了"+fileName+"，路径"+path + "/" + newFileName+"。");
				logInfo.setFileName(fileName);
				logInfo.setUrl(path + "/" + newFileName);
				logInfo.setIpAddress(shiroUser.getIpAddress());

				logInfoService.insert(logInfo);
			}
			
			return Utils.JsonUtil.toJson(AjaxObject.newData(map, "上传成功."));
		} catch (IOException e) {
			e.printStackTrace();
			return AjaxObject.newError("IOException").toString();
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param request
	 * @param response
	 * @param url
	 * 
	 * @return
	 * @author longfei
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public String download(HttpServletRequest request, HttpServletResponse response, String url) {
		String filePath = FileUtils.getFileStorePath(request) + File.separator + url;
		InputStream input = null;
		try {
			input = new FileInputStream(filePath);
		} catch (FileNotFoundException e) {
			//return "文件没找到或已被删除。";
			return "error/file_not_found";
		}
		String fileName = "";
		int lastIndex = url.lastIndexOf("/");
		if (lastIndex >= 0) {
			fileName = url.substring(lastIndex + 1).toLowerCase();
		}
		ServletUtils.setFileDownloadHeader(request, response, fileName);
		try {
			IOUtils.copy(input, response.getOutputStream());
		} catch (Exception e) {
			//return "文件下载出错。";
			return "error/file_not_found";
		} finally {
			IOUtils.closeQuietly(input);
		}
		
		return null;
	}

}
